#include "factory.h"
int factory_init(pfactory_t p,int threadnum,int quecapacity)
{
    bzero(p,sizeof(factory_t));
    p->threadnum=threadnum;
    p->startflag=0;
    pthread_cond_init(&p->cond,NULL);
    que_init(&p->que,quecapacity);
    //为存放线程id的数组申请空间
    p->pthid=(pthread_t*)calloc(threadnum,sizeof(pthread_t));
    return 0;
}
void *threadfunc(void *p)
{
    pfactory_t pfac=(pfactory_t)p;
    pque_t pque=&pfac->que;
    pnode_t ptask;
    while(1)
    {
        pthread_mutex_lock(&pque->q_mutex);
        if(0==pque->qsize)
        {
            pthread_cond_wait(&pfac->cond,&pque->q_mutex);
        }
        que_get(pque,&ptask);
        pthread_mutex_unlock(&pque->q_mutex);
        trans_file(ptask->newfd);
        free(ptask);
        printf("ONE task done!\n");
    }
}
int factory_start(pfactory_t p)
{
    if(!p->startflag)
    {
        for(int i=0;i<p->threadnum;++i)
        {
            pthread_create(p->pthid+i,NULL,threadfunc,p);
        }
        p->startflag=1;
    }
    return 0;
}
